package server.java.autoduel.Cars;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;

import server.java.autoduel.Util.XmlFileFilter;

import com.thoughtworks.xstream.XStream;

/**
 * Provides a set of powerplant blueprints for the game to work with
 * 
 * @author Ian Axelrod
 * @author Liz Ha
 * @author Andrew Muldowney
 * @author Edward Futch
 */
public class PowerPlantFactory {

	/**
	 * The data directory powerplant xml files are present in
	 */
	private final static String data_dir = "./data/powerplants/";

	/**
	 * A hash map of all the powerplants, keyed by their name
	 */
	private static HashMap<String, PowerPlant> powerplants;

	/**
	 * Loads up all the powerplant data from the server filesystem
	 * 
	 * @throws IOException
	 */
	public static void loadPowerPlants() throws IOException {
		final File dir = new File(PowerPlantFactory.data_dir);
		final File[] files = dir.listFiles(new XmlFileFilter());
		PowerPlantFactory.powerplants = new HashMap<String, PowerPlant>();

		for (final File file : files) {
			final FileInputStream reader = new FileInputStream(file);
			final byte[] buf = new byte[(int) file.length()];

			reader.read(buf);
			reader.close();
			final XStream xstream = new XStream();
			xstream.alias("PowerPlant", PowerPlant.class);
			final PowerPlant powerplant = (PowerPlant) xstream
					.fromXML(new String(buf));
			PowerPlantFactory.powerplants.put(powerplant.getName(), powerplant);
		}
	}

	/**
	 * Provides the requested powerplant to the caller
	 * 
	 * @param name
	 *            the name of the powerplant to create
	 * @return a copy of the requested powerplant
	 */
	public static PowerPlant providePowerPlant(String name) {
		return PowerPlantFactory.powerplants.get(name).copy();
	}

	/**
	 * Provides to the caller a copy of the internal list of powerplants
	 * available
	 * 
	 * @return the powerplants available in this factory
	 */
	public static ArrayList<PowerPlant> providePowerPlants() {
		final ArrayList<PowerPlant> powerPlantsCopy = new ArrayList<PowerPlant>();

		for (final PowerPlant powerplant : PowerPlantFactory.powerplants
				.values()) {
			powerPlantsCopy.add(powerplant.copy());
		}
		return powerPlantsCopy;
	}
}